<?php

    require_once(dirname(__FILE__).'/../../globals.inc');
    require_once(dirname(__FILE__).'/private/gameform.inc');

    $mikron->Page->StartBody();
    if(is_null($mikron->Users->CurrentUser()->user))
    {
        echo '{{$PLEASE_REG}}';
        $mikron->Page->EndBody();
        exit;
    }
    
    $cab = $mikron->Users->CurrentUser()->user;
    $played = isset($_GET['play'])?1:0;
    $win = isset($_GET['win'])?1:0;
    $lose = isset($_GET['lose'])?1:0;

    $code = $_GET['code'];
    $games = $mikron->Queries->Query('GAME', null, new Criterion('code', $code));
    if($games->count() == 0)
    {
        GoToPage('/');
    }
    $game = $games->fetch();
    $games->free();

    $max_game_count = $game->id == 1?7:999;
    $must_play_code = $mikron->Site->AllowPlay($game, $max_game_count);

    $rate = $game->rate->value;
    $can_lost = $rate;
    $can_win = $game_prize->value;

    if($game->id == 1)
    {
        $rate = $must_play_code==0?$rate:20;
        $can_lost = 0;
    }

    /*
        echo $game->name->value, '<br />';
        echo $must_play_code, '<br />';
        echo $rate;
    */

    $cr = new Criteria();
    $cr->Add(new Criterion('game', $game->id));
    $cr->Add(new Criterion('dt', $dtfilter, CR_MOREOREQUAL));
    $cr->Add(new Criterion('user', $mikron->Users->CurrentUser()->user->id));
    $play_count = $mikron->Queries->QueryCount('PLAYLOG', null, $cr);
    
    if($win)
    {
        echo sprintf('<h1>Поздравляем! Вы выиграли %s руб.</h1>', round((intval($_GET['win']))/100));
        if($game->id == 1)
        {
            $game5 = new GAME(2);
            echo sprintf('Попробуйте теперь сыграть в игру <a href="/games/%s/">%s</a> и выиграть %s рублей.', $game5->code->value, $game5->name->value, round($game5->prize->value/100,2));
        }
    }
    elseif($lose)
    {
        $lose_sum = intval($_GET['lose']);
        if($lose_sum > 0)
        {
            echo sprintf('<h1>Вы проиграли %s руб.</h1>', round($lose_sum/100, 2));
        }
        else
        {
            if($play_count>0)
            {
            echo '<h1>Вы не выиграли.</h1>';
            }
        }
    }    

    if($can_lost > $cab->amount->value)
    {
        echo '<h2>У Вас недостаточно денег на балансе для дальнейшей игры.</h2>';
        $mikron->Page->EndBody();
        return;
    }

    if($play_count >= $max_game_count)
    {
        echo 'Вы уже сыграли сегодня максимальное допустимое количество раз.';   
    }
    else
    {
        if($played)
        {

            $save_obj = Array();

            $game->bank->value += $rate;
            $game->plays->value = $game->plays->value + 1;

            $playlog = new PLAYLOG();
            $playlog->game->value = $game->id;
            $playlog->user->value = $cab->id;
            $playlog->amount->value = $rate;
            $playlog->ip->value = $mikron->Users->CurrentUser()->ip();
            $save_obj[] = $playlog;
            $save_obj[] = $game;
            $save_obj[] = $cab;

                if($can_lost > 0)
                {
                    $rate_log = ChangeCabinetBalance($cab, 12, -$can_lost, 0, 0, 0, 0);
                    $save_obj[] = $rate_log;
                }

            if($game->bank->value >= $game->needsum->value)
            {
                $div = $game->needsum->value - $game->bank->value;
                $game->bank->value = $game->bank->value - $game->needsum->value;
                $winkey = md5(time().'secretkey');
                $win = new T_WIN();
                $win->game->value = $game->id;
                $win->winkey->value = $winkey;
                $save_obj[] = $win;

                $cab->winamount->value += $game->prize->value;

                $win->state->value = 2;
                $win->cabinet->value = $cab->id;
                $win->amount->value = $game->prize->value;
                $foplog = ChangeCabinetBalance($cab, 9, $win->amount->value, 0, 0, 0, 0);
                /**
                * Начисление рефералу
                */
                $ref = $cab->referal->value;
                if(is_object($ref))
                {
                    $ref_sum = $win->amount->value * 0.1;
                    $foplog_ref = ChangeCabinetBalance($ref, 7, $ref_sum, 0, 0, 0, 0);
                    $ref->refamount->value += $ref_sum;
                    OperationLogEcp($foplog_ref, $ref, $cab);
                    $save_obj[] = $foplog_ref;
                    $save_obj[] = $ref;
                }
                OperationLogEcp($foplog, $cab);
                $save_obj[] = $foplog;
                
                $mikron->EntityManager->Save($save_obj);
                $mikron->Tools->GoToPage($mikron->Tools->MakePath('?win='.$win->amount->value));
            }
            else
            {
                $mikron->EntityManager->Save($save_obj);
                $mikron->Tools->GoToPage($mikron->Tools->MakePath('?lose='.$can_lost));
            }
        }
        $cr = new Criteria();
        $cr->Add(new Criterion('game', $game->id));
        $adv_items = $mikron->Queries->Query('GAME_ADV', null, $cr);
        $i = 0;
        $ads_text = null;
        while($item = $adv_items->fetch())
        {
            if($i == $play_count)
            {
                $ads_text = $item->ads->value;
                break;
            }
            $i++;
        }
        if($game->id == 1)
        {
            $chance_text = 'первый';
            switch($play_count+1)
            {
               case 1:$chance_text='первый';break; 
               case 2:$chance_text='второй';break; 
               case 3:$chance_text='треттий';break; 
               case 4:$chance_text='четвертый';break; 
               case 5:$chance_text='пятый';break; 
               case 6:$chance_text='шестой';break; 
               case 7:$chance_text='седьмой';break; 
            }
            echo sprintf('{{nicewindow style=white caption="Игра %s, у вас %s шанс из семи выиграть рубль!"}}', $game->name->value, $chance_text);
        }
        else
        {
            echo sprintf('{{nicewindow style=white caption="Игра %s, у вас один шанс из %s выиграть %s руб!"}}', $game->name->value, ceil($game->needsum->value / $rate), $game->prize->value / 100 );
            echo sprintf('<h2>Внимание!</h2> Данная игра на ставку,
            Вы можете потерять %s руб.<br />', round($can_lost/100,2));
        }
        if($game->id==1)
        {
            echo $ads_text, '<br />';
        }
        echo sprintf('<a href="%s">Играю!</a>', $mikron->Tools->MakePath('?play'));
        echo '{{/nicewindow}}';
    }

    $mikron->Page->EndBody();
    return;

    /*
        echo $_GET['code'];
        $mikron->Site->CheckAllowPlay($game);
        require_once(dirname(__FILE__).'/gameads.inc');
        return $mikron->Page->EndBody();
    */

    if(is_null($mikron->Users->CurrentUser()->user))
    {
        ?>{{$PLEASE_REG}}<?php
        $mikron->Page->EndBody();
        exit;
    }

    $code = $_GET['code'];
    $game = $mikron->Queries->Query('GAME', null, new Criterion('code', $code));
    if($game->count() == 0)
    {
        GoToPage('/');
    }
    $game = $game->fetch();

    $mikron->Site->CheckAllowPlay($game);

    $gform = new game_form($game->id);
    $gform->addIntValue('value', true);
    $gform->addIntValue('usersession', true);

    $must_play_code = $mikron->Site->AllowPlay($gform->gameobject);

        if(!($mikron->Users->Logged()) || ($mikron->Site->AllowPlay($game) == 2))
        {
            $gform->AddButton("play_grey", 1, "Играть", null, null, true, true);   
            $gform->AddButton("gamelist", 2, "К списку игр", "/");         
        }
        else
        {
            $gform->AddButton("play_grey", 1, "Играть", null, null, true, false);
            $gform->AddButton("playbutton", 2, "Играть", "#", "onclick='return PlayGame();' ");
            $gform->AddButton("gamelist", 2, "К списку игр", "/");
            ?>
            <script type="text/javascript">
                $(document).ready(function()
                {
                    var pb = document.getElementById('play_grey');
                    pb.style.display = 'none';
                    pb = document.getElementById('playbutton');
                    pb.style.display = '';
                });
            </script>
            <?php
        }
        $gform->AddButton('waitimage', 44, "<img src='/mikron/sites/7chances2/images/wait.gif' alt='wait'>", "#", null, false, false);

    $gform->start();

    $gform->begin();
        $ret = StartGame($gform);
        if($ret)
        {
            $game = $gform->gameobject;
            $games = $mikron->Queries->Query('GAME', null, new Criterion('id', $game->id, CR_MORE));
            if($games->count() == 0)
            {
                $games = $mikron->Queries->Query('GAME');
            }
            $game = $games->fetch();
            echo sprintf('<br /><a href="%s">Перейти</a> к игре «%s».', $game->ToURL(), $game->name->value);
        }
    $gform->end();
    $mikron->Page->EndBody();
    exit;

    function StartGame(game_form $gform)
    {

        global $mikron;
        $game = $gform->gameobject;

        if(is_null($mikron->Users->CurrentUser()->user))
        {
            // echo $game->content->value;
            return false;
        }

        if(isset($_GET['lose']))
        {
            echo '{{$LOSEMESSAGE}}';
            return true;
        }
        if(isset($_GET['win']))
        {
            echo '{{$WINMESSAGE}}';
            return true;
        }

        if($gform->IsExecuted())
        {
            $save_obj = Array();
            
            if($game->locked->value == 1)
            {
               $rate = 0; 
            }
            else
            {
                $rate = $mikron->ACL->hasRole('premiumaccount') ? $game->ratepremium->value : $game->rate->value;
                $must_play_code = $mikron->Site->AllowPlay($gform->gameobject);
                /**
                * Если игрок не резидент РФ, либо повтор IP или его первых 3-х октетов
                */
                if($must_play_code == 2)
                {
                    GoToPage($_SERVER['REQUEST_URI'].'?lose');
                }
                elseif($must_play_code != 0)
                {
                    $rate = 0;
                }
                /**
                * если игра не засчиталась из-за того, что игрок не резидент РФ
                */
                if(($rate == 0) && ($must_play_code == 1))
                {
                    $churkasaloed = $game->churkasaloed->value;
                    $game->churkasaloed->value += 1;
                    $churkasaloedlimit = $game->churkasaloedlimit->value;
                    if($game->churkasaloed->value % $churkasaloedlimit == 0)
                    {
                        $rate = $game->rate->value;
                    }
                }
            }
            
            /*** АНТИЧИТЕР ***/
            $anti_cheater = 1;
            $anti_cheater_src = null;
            try
            {
                $anti_cheater_src = $gform->usersession;
                $anti_cheater = $anti_cheater_src;
                if(is_numeric($anti_cheater))
                {
                    $anti_cheater = (int)$anti_cheater;
                }
                else
                {
                    $anti_cheater = 1;
                }
            }
            catch(Exception $ex)
            {
                $anti_cheater = 1;
            }

            if($anti_cheater != 0)
            {
                $code = $game->code->value;
                if($game->code->value != 'freebie500')
                {
                    $sm = new SECURITY_MESSAGES();
                    $sm->source->value = 'Игровая форма';
                    $sm->message->value = 'Игра «'.$code.'» во фрейме. Фрейм '.$anti_cheater_src;
                    $sm->economy->value = $rate;
                    $sm->Save();
                    $mikron->Tools->GoToPage($_SERVER['REQUEST_URI'].'?lose');
                }
            }

            $game->bank->value = $game->bank->value + $rate;
            $game->plays->value = $game->plays->value + 1;

            $cab = $mikron->Users->CurrentUser()->user;

            $playlog = new PLAYLOG();
            $playlog->game->value = $game->id;
            $playlog->user->value = $cab->id;
            $playlog->amount->value = $rate;
            $playlog->ip->value = $mikron->Users->CurrentUser()->ip();
            $save_obj[] = $playlog;

            if($game->bank->value >= $game->needsum->value)
            {
                $div = $game->needsum->value - $game->bank->value;
                $game->bank->value = $game->bank->value - $game->needsum->value;
                $winkey = md5(time().'secretkey');
                $win = new T_WIN();
                $win->game->value = $game->id;
                $win->winkey->value = $winkey;
                $win->Save();
                $game->Save();

                $cab->winamount->value += $game->prize->value;

                $win->state->value = 2;
                $win->cabinet->value = $cab->id;
                $win->amount->value = $game->prize->value;
                $foplog = ChangeCabinetBalance($cab, 9, $win->amount->value, 0, 0, 0, 0);
                /**
                * Начисление рефералу
                */
                $ref = $cab->referal->value;
                if(is_object($ref))
                {
                    $ref_sum = $win->amount->value * 0.1;
                    $foplog_ref = ChangeCabinetBalance($ref, 7, $ref_sum, 0, 0, 0, 0);
                    $ref->refamount->value += $ref_sum;
                    OperationLogEcp($foplog_ref, $ref, $cab);
                    $save_obj[] = $foplog_ref;
                    $save_obj[] = $ref;
                }
                OperationLogEcp($foplog, $cab);
                $save_obj[] = $foplog;
                $save_obj[] = $cab;
                $save_obj[] = $win;
                $mikron->EntityManager->Save($save_obj);
                GoToPage($_SERVER['REQUEST_URI'].'?win');

                return true;
            }
            else
            {
                $game->Save();
                $mikron->EntityManager->Save($save_obj);
                GoToPage($_SERVER['REQUEST_URI'].'?lose');
            }
        }
        else
        {
            if(!$mikron->Users->CurrentUser()->hasRole('premiumaccount'))
            {
                if($mikron->Site->Version == 3)
                {
                    echo $game->content->value;
                }
                elseif($mikron->Site->Version == 4)
                {
                    require_once(dirname(__FILE__).'/gameads.inc');
                }
            }
        }
        // echo '<div style="color: #ccc; ">Набрано ', $game->bank->value.' из '.$game->needsum->value, ' копеек.</div>';
    }

?>